#!/bin/bash

##########################################
# this module defines some general actions
# NOTE: this is a partial module of dfproxym
##########################################

#############################
# log function
#############################

_info() {
  echo "[$(date +'%Y-%m-%d %H:%M:%S')]: $*"
}

_warn() {
  echo -e "\033[1;33m[$(date +'%Y-%m-%d %H:%M:%S')]: $*\033[0m" >&2
}
_err() {
  echo -e "\033[1;31m[$(date +'%Y-%m-%d %H:%M:%S')]: $*\033[0m" >&2
  exit 1
}

#############################
# @param: file_path
# @param: target_regex
# @param: replace_string
#############################
replace_regex_or_append_in_file() {
  local file_path=${1:-""}
  local target_regex=${2:-""}
  local replace_string=${3:-""}
  [[ -f "$file_path" ]] || _err "file $file_path does not exist and can not replace $target_regex -> $replace_string"

  # replace target_regex or append replace_string
  sed -E -i -e "s|${target_regex}|${replace_string}|g" "${file_path}"
  local exist=""
  exist=$(grep "${replace_string}" "${file_path}")
  [[ ! -z exist ]] || echo "${replace_string}" >>"${file_path}"
}

###########################
# remove comment from jsonc
# TODO: this function can only remove // from json
# @param: file_path
###########################
strip_jsonc() {
  local file_path=${1:-""}
  [[ -f "$file_path" ]] || _err "file $file_path does not exist and can not strip it as jsonc"
  awk '
 {
    out = ""; esc = 0; in_str = 0
    for (i = 1; i <= length($0); i++) {
      c = substr($0, i, 1)

      # 处理转义
      if (esc) { out = out c; esc = 0; continue }
      if (c == "\\") { out = out c; esc = 1; continue }

      # 字符串边界
      if (c == "\"") { in_str = !in_str; out = out c; continue }

      # 只有不在字符串里才尝试匹配 "//"
      if (!in_str && c == "/" && i < length($0) && substr($0, i + 1, 1) == "/") {
        # 匹配成功，直接丢弃本行剩余部分
        break
      }
      out = out c
    }
    print out
  } 
  ' "$file_path"
}

###########################
# check if opt exist in args
# @param target: target opt
# @param args: a list of arguements
# @return 0: exist | 1: not exist
###########################
has_opt() {
  local target="${1}"
  local arg
  for arg in ${@:2}; do
    [[ $arg == "$target" ]] && return 0
  done
  return 1
}
